package com.appkudos.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.appkudos.model.App;
import com.appkudos.model.Category;
import com.appkudos.model.Group;
import com.appkudos.model.Recommendation;
import com.appkudos.model.User;

public class GroupController extends Controller {
	String response = "";
	String output = "";
	ArrayList<NameValuePair> nameValuePairs;

	public GroupController(){
		
	}
	
	/***
	 * Returns how many times an appid has been recommended in groupid
	 * @return int
	 */
	public Integer getNRec(String appid, String groupid) {
	    nameValuePairs = new ArrayList<NameValuePair>();
	    nameValuePairs.add(new BasicNameValuePair("function","getNRec"));
	    nameValuePairs.add(new BasicNameValuePair("groupid",groupid));
	    nameValuePairs.add(new BasicNameValuePair("appid",appid));
	    
	    response = sendData(URL_GROUP_QUERIES, nameValuePairs);
	    Integer manytimes = null;
	    
	    //parse json data
	    try{
	    	JSONArray jArray = new JSONArray("["+response+"]");
    		JSONObject json_data = jArray.getJSONObject(0);
    		if(json_data.has("ERROR")){
            	//output += json_data.getString("ERROR");
            }else{
	            manytimes = Integer.parseInt(json_data.getString("counted"));
	            
	        }
            
	    }catch(JSONException e){
	    		output = "Error";
	    }
	   	  
	    return manytimes;
	}
	
	
	/***
	 * Create a new category
	 * @param name
	 * @return true if successful operation
	 */
	public boolean createCategory(String name) {
		    nameValuePairs = new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("function","createCategory"));
		    nameValuePairs.add(new BasicNameValuePair("name",name));
		    
		    response = sendData(URL_GROUP_QUERIES, nameValuePairs);
		    
		    return executeOperation(response);
	}
	
	/***
	 * Gets all category names and ids (for Create Group screen)
	 * @return List<Category> of all categories
	 */
	public List<Category> getAllCategories() {
	    nameValuePairs = new ArrayList<NameValuePair>();
	    nameValuePairs.add(new BasicNameValuePair("function","getAllCategories"));
	    
	    response = sendData(URL_GROUP_QUERIES, nameValuePairs);
	    List<Category> returnCats = new ArrayList<Category>();
	    
	    //parse json data
	    try{
	    	JSONArray jArray = new JSONArray("["+response+"]");
    		for(int i=0;i<jArray.length();i++){
            	JSONObject json_data = jArray.getJSONObject(i);
            	if(json_data.has("ERROR")){
            		//output += json_data.getString("ERROR");
            	}else{
	            	returnCats.add(new Category(json_data.getString("catid"), json_data.getString("categoryName")));
	            }
            }
	    }catch(JSONException e){
	    		output = "Error";
	    }
	   	  
	    return returnCats;
	}
	
	/***
	 * createGroup($name, $desc, $catid) : returns boolean
getGroupProfile($groupid) : returns String array[name,desc,dateCreated, String array[recid, message, sender, recipient, dateSent]]
getAppsOfGroup($groupid) : returns String array[[nameApp, idApp]]
getMembersOfGroup($groupid) : returns [[username,firstname,lastname,dateCreated]]
searchForGroup($keyword) : returns[[groupid,name,desc,dateCreated]]
joinGroup($groupid) : returns boolean
	 */
	
	
	/***
	 * Create a new group
	 * @param name
	 * @param desc
	 * @param catid
	 * @return True if created successfully
	 */
	public boolean createGroup(String name, String desc, String catid) {
		    nameValuePairs = new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("function","createGroup"));
		    nameValuePairs.add(new BasicNameValuePair("name",name));
		    nameValuePairs.add(new BasicNameValuePair("desc",desc));
		    nameValuePairs.add(new BasicNameValuePair("catid",catid));
		    
		    response = sendData(URL_GROUP_QUERIES, nameValuePairs);
		    
		    return executeOperation(response);
	}
	
	
	/***
	 * Gets all parts of group info
	 * @param groupid
	 * @return Group object for specified groupid
	 */
	public Group getGroupById(String groupid) {
		    nameValuePairs = new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("function","getGroupProfile"));
		    nameValuePairs.add(new BasicNameValuePair("groupid",groupid));
		    
		    response = sendData(URL_GROUP_QUERIES, nameValuePairs);
		    Group returnGroup = null;
		    
		    //parse json data
		    try{
		    	JSONArray jArray = new JSONArray("["+response+"]");
	    		for(int i=0;i<jArray.length();i++){
	            	JSONObject json_data = jArray.getJSONObject(i);
	            	if(json_data.has("ERROR")){
	            		//output += json_data.getString("ERROR");
	            	}else{
	            		Category c = new Category(json_data.getString("catid"), json_data.getString("categoryName"));
		            	returnGroup = new Group(groupid, 
		            			json_data.getString("name"), json_data.getString("desc"),
		            			c, json_data.getString("dateCreated"));
		            }
	            }
		    }catch(JSONException e){
		    	
		    }
		   	  
		    return returnGroup;
	}
	
	/***
	 * Gets all parts of group info
	 * @param groupName
	 * @return Group object for specified group name
	 */
	public Group getGroupByName(String groupName) {
		    nameValuePairs = new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("function","retrieveGroupByName"));
		    nameValuePairs.add(new BasicNameValuePair("name", groupName));
		    
		    response = sendData(URL_GROUP_QUERIES, nameValuePairs);
		    Group returnGroup = null;
		    
		    //parse json data
		    try{
		    	JSONArray jArray = new JSONArray("["+response+"]");
	    		for(int i=0;i<jArray.length();i++){
	            	JSONObject json_data = jArray.getJSONObject(i);
	            	if(json_data.has("ERROR")){
	            		//output += json_data.getString("ERROR");
	            	}else{
	            		Category c = new Category(json_data.getString("catid"), json_data.getString("categoryName"));
		            	returnGroup = new Group(json_data.getString("groupid"), 
		            			json_data.getString("name"), json_data.getString("desc"),
		            			c, json_data.getString("dateCreated"));
		            }
	            }
		    }catch(JSONException e){
		    	
		    }
		   	  
		    return returnGroup;
	}	
	
	/***
	 * Gets all recs for this group
	 * @param groupid
	 * @return List<Rec> for specified Group
	 */
	public List<Recommendation> getGroupRecs(String groupid) {
		    nameValuePairs = new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("function","getRecsForGroup"));
		    nameValuePairs.add(new BasicNameValuePair("groupid",groupid));
		    
		    response = sendData(URL_GROUP_QUERIES, nameValuePairs);
		    List<Recommendation> returnRecs = new ArrayList<Recommendation>();
		    
		    //parse json data
		    try{
		    	JSONArray jArray = new JSONArray("["+response+"]");
	    		for(int i=0;i<jArray.length();i++){
	            	JSONObject json_data = jArray.getJSONObject(i);
	            	if(json_data.has("ERROR")){
	            		//output += json_data.getString("ERROR");
	            	}else{
	            		returnRecs.add(new Recommendation(json_data.getString("recid"), 
	            				json_data.getString("message"), 
	            				json_data.getString("sender"),
	            				json_data.getString("recipient"), json_data.getString("dateSent"),
	            				true, json_data.getString("appid")));
		            }
	            }
		    }catch(JSONException e){
		    		
		    }
		   	  
		    return returnRecs;
	}	
	
	/***
	 * Gets all recent recs for this group
	 * @param groupid
	 * @return List<Rec> for recommendations sent in the past month
	 */
	public List<Recommendation> getRecentGroupRecs(String groupid) {
		    nameValuePairs = new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("function","retrieveGroupRecentApps"));
		    nameValuePairs.add(new BasicNameValuePair("id",groupid));
		    
		    response = sendData(URL_GROUP_QUERIES, nameValuePairs);
		    List<Recommendation> returnRecs = new ArrayList<Recommendation>();
		    
		    //parse json data
		    try{
		    	JSONArray jArray = new JSONArray("["+response+"]");
	    		for(int i=0;i<jArray.length();i++){
	            	JSONObject json_data = jArray.getJSONObject(i);
	            	if(json_data.has("ERROR")){
	            		//output += json_data.getString("ERROR");
	            	}else{
	            		returnRecs.add(new Recommendation(json_data.getString("recid"), 
	            				json_data.getString("message"), json_data.getString("sender"),
	            				groupid, json_data.getString("dateSent")));
		            }
	            }
		    }catch(JSONException e){
		    		
		    }
		   	  
		    return returnRecs;
	}		

	/***
	 * Gets all apps recommended to this group
	 * @param groupid
	 * @return List<App> with recommendations to this group
	 */
	public List<App> getAppsForGroup(String groupid) {
		    nameValuePairs = new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("function","getAppsOfGroup"));
		    nameValuePairs.add(new BasicNameValuePair("groupid",groupid));
		    
		    response = sendData(URL_GROUP_QUERIES, nameValuePairs);
		    List<App> returnApps = new ArrayList<App>();
		    
		    //parse json data
		    try{
		    	JSONArray jArray = new JSONArray("["+response+"]");
	    		for(int i=0;i<jArray.length();i++){
	            	JSONObject json_data = jArray.getJSONObject(i);
	            	if(json_data.has("ERROR")){
	            		//output += json_data.getString("ERROR");
	            	}else{
	            		returnApps.add(new App(json_data.getString("appid"), 
	            				json_data.getString("name"), json_data.getString("desc")));
		            }
	            }
		    }catch(JSONException e){
		    		
		    }
		   	  
		    return returnApps;
	}	

	/***
	 * Gets all members who have joined this group
	 * @param groupid
	 * @return List<User> who have joined this group
	 */
	public List<User> getGroupMembers(String groupid) {
		    nameValuePairs = new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("function","getMembersOfGroup"));
		    nameValuePairs.add(new BasicNameValuePair("groupid",groupid));
		    
		    response = sendData(URL_GROUP_QUERIES, nameValuePairs);
		    List<User> returnUsers = new ArrayList<User>();
		    
		    //parse json data
		    try{
		    	JSONArray jArray = new JSONArray("["+response+"]");
	    		for(int i=0;i<jArray.length();i++){
	            	JSONObject json_data = jArray.getJSONObject(i);
	            	if(json_data.has("ERROR")){
	            		//output += json_data.getString("ERROR");
	            	}else{
	            		returnUsers.add(new User(json_data.getString("username"), 
	            				json_data.getString("firstname"), json_data.getString("lastname"), 
	            				json_data.getString("dateJoined")));
		            }
	            }
		    }catch(JSONException e){
		    		
		    }
		   	  
		    return returnUsers;
	}		
	
	/***
	 * Gets all groups who match the input keyword
	 * @param keyword to search for
	 * @return List<Group> of search results
	 */
	public List<Group> searchForGroup(String keyword) {
		    nameValuePairs = new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("function","searchForGroup"));
		    nameValuePairs.add(new BasicNameValuePair("keyword",keyword));
		    
		    response = sendData(URL_GROUP_QUERIES, nameValuePairs);
		    List<Group> returnGroups = new ArrayList<Group>();
		    
		    //parse json data
		    try{
		    	JSONArray jArray = new JSONArray("["+response+"]");
	    		for(int i=0;i<jArray.length();i++){
	            	JSONObject json_data = jArray.getJSONObject(i);
	            	if(json_data.has("ERROR")){
	            		//output += json_data.getString("ERROR");
	            	}else{
	            		returnGroups.add(new Group(json_data.getString("groupid"), 
	            				json_data.getString("name"), json_data.getString("desc"), 
	            				new Category(json_data.getString("catid"),json_data.getString("categoryName")), 
	            				json_data.getString("dateCreated")));
		            }
	            }
		    }catch(JSONException e){
		    		
		    }
		   	  
		    return returnGroups;
	}		
	
	/***
	 * Gets all groups who match the input keyword
	 * @param groupid
	 * @return List<Group> of search results
	 */
	public List<Group> getAllGroups() {
		    nameValuePairs = new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("function","retrieveAllGroups"));
		    
		    response = sendData(URL_GROUP_QUERIES, nameValuePairs);
		    List<Group> returnGroups = new ArrayList<Group>();
		    
		    //parse json data
		    try{
		    	JSONArray jArray = new JSONArray("["+response+"]");
	    		for(int i=0;i<jArray.length();i++){
	            	JSONObject json_data = jArray.getJSONObject(i);
	            	if(json_data.has("ERROR")){
	            		//output += json_data.getString("ERROR");
	            	}else{
	            		returnGroups.add(new Group(json_data.getString("groupid"), 
	            				json_data.getString("name"), json_data.getString("desc"), 
	            				new Category(json_data.getString("catid"),json_data.getString("categoryName")), 
	            				json_data.getString("dateCreated")));
		            }
	            }
		    }catch(JSONException e){
		    		
		    }
		   	  
		    return returnGroups;
	}		
	
	/***
	 * Gets all groups who match the input keyword
	 * @param groupid
	 * @return List<Group> of search results
	 */
	public List<Group> getAllGroupsInCategory(String catid) {
		    nameValuePairs = new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("function","retrieveAllGroupsInCategory"));
		    nameValuePairs.add(new BasicNameValuePair("cat",catid));
		    
		    response = sendData(URL_GROUP_QUERIES, nameValuePairs);
		    List<Group> returnGroups = new ArrayList<Group>();
		    
		    //parse json data
		    try{
		    	JSONArray jArray = new JSONArray("["+response+"]");
	    		for(int i=0;i<jArray.length();i++){
	            	JSONObject json_data = jArray.getJSONObject(i);
	            	if(json_data.has("ERROR")){
	            		//output += json_data.getString("ERROR");
	            	}else{
	            		returnGroups.add(new Group(json_data.getString("groupid"), 
	            				json_data.getString("name"), json_data.getString("desc"), 
	            				new Category(json_data.getString("catid"),json_data.getString("categoryName")), 
	            				json_data.getString("dateCreated")));
		            }
	            }
		    }catch(JSONException e){
		    		
		    }
		   	  
		    return returnGroups;
	}			
	
}